package com.hotel.front;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.EntityName;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;

@SuppressWarnings("serial")
public class RemoveFactory extends HttpServlet {

	protected static DatastoreService datastore = DatastoreServiceFactory
			.getDatastoreService();

	//http://localhost:8080/removeFactory?func=RemoveEntity&type=entityName
	//http://localhost:8080/removeFactory?func=RemoveRelatedReservation

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, IllegalArgumentException {
		resp.setContentType("text/plain; charset=utf-8");
		resp.setHeader("Cache-Control", "no-cache");

		String func = req.getParameter("func");	
		try{
			
			if(func.equals("RemoveEntity"))
				Remove(req,resp);
			else if(func.equals("RemoveRelatedReservation"))
				RemoveRelatedReservation(req,resp);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void Remove(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		try{
			String type = req.getParameter("type");
			
			DeleteEntityType(type);
			
			resp.getWriter().println(type + " Removed");
			
		}catch(Exception ex)
		{
			resp.getWriter().println("Remove Fail");
		}
	}
	
	private void RemoveRelatedReservation(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		try{
			DeleteEntityType(EntityName.Payment);
			DeleteEntityType(EntityName.SubPayment);
			DeleteEntityType(EntityName.Charge);
			DeleteEntityType(EntityName.SubReservation);
			DeleteEntityType(EntityName.Reservation);
			DeleteEntityType(EntityName.AuditTrail);
			DeleteEntityType(EntityName.PackageByDate);
			
			resp.getWriter().println("Related Reservation Removed");
			
		}catch(Exception ex)
		{
			resp.getWriter().println("Remove Fail");
		}
	}

	private void DeleteEntityType(String entityType)
	{
		List<Entity> list = GetEntityType(entityType);
		for(Entity e : list)
			datastore.delete(e.getKey());
	}
	
	private List<Entity> GetEntityType(String entityType)
	{
		Query q = new Query(entityType);
		
		return datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
	}
}
